<template>
	<view class="all">
		<div class="add">
			<div class="title">添加照片</div>
			<div class="des">
				<u-input v-model.trim="description" placeholder="请输入照片描述" type="textarea"></u-input>
			</div>
			<u-image width="50%" height="200rpx" :src="''" error-icon="photo" @click="manualUpload"></u-image>
		</div>
		<div class="img-show" v-for="item in imgs" :key="item.img_id">
			<div class="des">
				{{ item.description ? item.description : '' }}
			</div>
			<u-image width="100%" height="800rpx" :src="item.url? item.url : ''"></u-image>
		</div>

	</view>
</template>

<script setup>
	import {
		ref,onMounted
	} from 'vue';
	import { uploadImg,getImagesByUserId } from '../../api/images.js'
	const description = ref('')
	const files = ref([])
	const imgs = ref([])
	const beforeUpload = (file) => {
		console.log('准备上传的文件：', file);
		files.value = file
		return true;
	}
	//获取图片列表
	const getImgs = async () => {
		const result = await getImagesByUserId({
			user_id:uni.getStorageSync('userInfo').user_id
		})
		imgs.value = result.data
	}
	const manualUpload = async () => {
		const res = await uni.chooseImage({
			count: 1, // 可选择的图片数量
			sizeType: ['compressed'], // 压缩图片
			sourceType: ['album', 'camera'] // 来源相册或相机
		});
		// 获取选择的图片临时路径
		const filePath = res.tempFiles[0].path;
		const file = await uni.request({
			url:filePath,
			method:'GET',
			responseType:'arraybuffer',
		})
		const base64String = uni.arrayBufferToBase64(file.data)
		const imageUrl = `data:image/png;base64,${base64String}`
		const result = await uploadImg({
			user_id:uni.getStorageSync('userInfo').user_id,
			description:description.value,
			create_time:new Date(),
			url:imageUrl
		})
		if(result.code == 1){
			uni.showToast({
				title:'上传成功',
				icon:'none',
			})
			getImgs()
			description.value = ''
		}
	};
	
	onMounted(() => {
		getImgs()
	})
</script>

<style scoped lang="scss">
	.all {
		padding: 10rpx;

		.title {
			text-align: center;
		}
	}

	.img-show {
		.des {
			margin: 20rpx 0;
			padding: 0 20rpx;
			font-size: 28rpx;
			line-height: 50rpx;
		}
	}
</style>